﻿namespace Fetches.Fetch.Utils.IdGenerator
{
    public class LockIdPopulator
    {
        protected long sequence = 0;
        protected long lastTimestamp = -1;

        public void populateId(IdTimer timer, Id id, IdMeta idMeta)
        {
            lock (this)
            {

                long timestamp = timer.GenTime();
                timer.ValidateTimestamp(lastTimestamp, timestamp);

                if (timestamp == lastTimestamp)
                {
                    sequence++;
                    sequence &= idMeta.GetSeqBitsMask();
                    if (sequence == 0)
                    {
                        timestamp = timer.TillNextTimeUnit(lastTimestamp);
                    }
                }
                else
                {
                    lastTimestamp = timestamp;
                    sequence = 0;
                }

                id.Seq=sequence;
                id.Time=timestamp;
            }
        }

        public void reset()
        {
            this.sequence = 0;
            this.lastTimestamp = -1;
        }
    }
}
